
package com.ifcar.app.activity.topic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.activity.HomePage;
import com.ifcar.app.activity.newspage.NewsFragment;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.fragment.NRPullLoadingListWithHeaderFrament;
import com.ifcar.app.model.Attitude;
import com.ifcar.app.model.Topic;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.rss.GetContent;
import com.ifcar.app.util.BaseImageDownloader;
import com.ifcar.app.util.BasePageViewAdapter;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.activity.R;

public class AttitudeFrament extends NRPullLoadingListWithHeaderFrament implements OnItemClickListener{

    private List<Map<String, Object>> mTopicList;

    // 这个用在adapter中,比mTopicList少一个
    private List<Map<String, Object>> mTopicAdapterList;

    private BasePageViewAdapter mTopicAdapter;

    private View mHeaderLay;
    
    BaseImageDownloader mImageDownloader;
    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag(Topic.TOPIC_ATTITUDE);
    }

    @Override
	public ListAdapter getAdapter() {
		return mTopicAdapter;
	}
    
    
    @Override
    public void onLoadingListViewAttached(LoadingListView loadingListView) {
        if (mHeaderLay == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            mHeaderLay = layoutInflater.inflate(R.layout.top_image_text, null);
            mHeaderLay.findViewById(R.id.top_tag).setVisibility(View.GONE);
        }
        
        if (mHeaderLay != null) {
            ListView listView = loadingListView.getListView();
            listView.addHeaderView(mHeaderLay);
        }
        
        if (mTopicAdapter != null && mTopicAdapter.getCount() > 0) {
            callLoadingListViewAddMoreView();
        }
        
        super.onLoadingListViewAttached(loadingListView);
        
        getListView().setOnItemClickListener(this);
        
    }

    @Override
    public void onLoadingListViewDetached(LoadingListView loadingListView) {
        super.onLoadingListViewDetached(loadingListView);
        if (mHeaderLay != null) {
            loadingListView.getListView().removeHeaderView(mHeaderLay);
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        if (mTopicAdapter != null) {
            mTopicAdapter.notifyDataSetChanged();
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 参数调整，在detailPage种做判断
        String type = "attitude";
        Bundle b = new Bundle();
        
        String idJsonString = StringUtil.createIdString(mTopicList);
        if(!TextUtils.isEmpty(idJsonString)){
        	b.putString(NewsFragment.ID_JSON_STRING, idJsonString);
        }
        
        // setIsReaded4TopicList(position, docId);
        String imgsrc = "";
        String digest = "";
        String url = "";
        String replyCount = "";
        String title = "";
        String ptime = "";
        String docId = "";

        if ((mTopicList.get(position)).get(GetColumnsInfo.DOCID_TAG) != null) {
            docId = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.DOCID_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.IMGSRC_TAG) != null) {
            imgsrc = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.IMGSRC_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.DIGEST_TAG) != null) {
            digest = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.DIGEST_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.REPLYCOUNT_TAG) != null) {
            replyCount = StringUtil.GetString(mTopicList.get(position)
                    .get(GetColumnsInfo.REPLYCOUNT_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.URL_TAG) != null) {
            url = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.URL_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.TITLE_TAG) != null) {
            title = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.TITLE_TAG));
        }
        if ((mTopicList.get(position)).get(GetColumnsInfo.PTIME_TAG) != null) {
            ptime = StringUtil.GetString(mTopicList.get(position).get(GetColumnsInfo.PTIME_TAG));
        }

        if (docId != null && !docId.equals("")) {
            b.putString(GetColumnsInfo.DOCID_TAG, docId); // 文章ID
            b.putString(HomePage.POSITION, "" + position); // 当前位置
            b.putString(GetColumnsInfo.TID_TAG, type); // 类型 另一面
            // 态度
            b.putBoolean(StringUtil.IS_TOPIC, true); // 
            b.putString(GetColumnsInfo.URL_TAG, url);
            b.putString(GetColumnsInfo.IMGSRC_TAG, imgsrc);
            b.putString(GetColumnsInfo.DIGEST_TAG, digest);
            b.putString(GetColumnsInfo.REPLYCOUNT_TAG, replyCount);
            b.putString(GetColumnsInfo.TITLE_TAG, title);
            b.putString(GetColumnsInfo.PTIME_TAG, ptime);

            Intent itemintent = new Intent(getActivity(), NewsPage.class);

            itemintent.putExtras(b);

            startActivity(itemintent);
        } else {
            Toast.makeText(getActivity(), "打开新闻正文失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);
        if (first) {
            startLoading();
        } 

        if (mTopicAdapter != null) {
            mTopicAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onLoading() {
        super.onLoading();

        // 加载本地数据,没有启用新线程
        List<Map<String, Object>> list = Attitude.getTopicListFromDB(getDb(), "attitude");
        Message msg = getHandler().obtainMessage(MSG_LOADING);
        msg.obj = list;
        getHandler().dispatchMessage(msg);
    }

    @Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result;
        
        if (list != null && list.size() > 0) {
            callLoadingListViewAddMoreView();
        }
        
        setData(list);
        
        if (mTopicAdapter != null && mTopicAdapter.getCount() > 0) {
        	if (isNeedRefresh()) {
				getHandler().postDelayed(new Runnable() {
					@Override
					public void run() {
						refresh();
					}
				}, 200);
			}
        } else {
            refresh();
        }

    }
    
    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mTopicAdapter == null);
        final Context context = getActivity();
        final SQLiteDatabase sqldb = getDb();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 取网络
                List<Map<String, Object>> list = GetContent.getAttitudeList(StringUtil.topic_url,
                        0, getLoadingNum(), context);

                if (list != null && list.size() > 0) {
                    sqldb.execSQL(
                            "delete from " + NewsSQLiteOpenHelper.NEWS_LIST_TABLE
                                    + " where news_col_id='attitude'");
                    Attitude.insertTopicListToDB(sqldb, list, "attitude", "");
                }
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);
        final Context context = getActivity();
        if(null!=context){
            StringUtil.clearOfflineDownloadRefreshTime(context);
        }
        List<Map<String, Object>> topicData = (List<Map<String, Object>>) result;
        
        if (topicData != null && topicData.size() > 0) {
            callLoadingListViewAddMoreView();
        } else if (mTopicAdapter == null || mTopicAdapter.getCount() == 0) {
            callLoadingListViewRemoveMoreView();
        }

        if (topicData != null && topicData.size() != 0) {
            callLoadingListViewCompleteLoading(true, true);
            setData(topicData);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
    }
    
    @Override
    protected void onLoadingMore() {
        super.onLoadingMore();
        final int num = getLoadingNum();
        final int start = (mTopicList == null || mTopicList.size() == 0) ? 0
                : getLoadingStart() + num;
        callLoadingListViewStartLoadingMore(start);
        final Context context = getActivity();
        // 取网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Map<String, Object>> list = GetContent.getAttitudeList(StringUtil.topic_url,
                        start, num, context);
                if (list != null) {

                    synchronized (AttitudeFrament.this) {
                        if (mTopicList != null) {
                            for (int i = 0; i < list.size(); i++) {
                                if (((HashMap<String, Object>) list.get(i))
                                        .get(StringUtil.TOPIC_DOCID) != null) {
                                    String docid2 = StringUtil
                                            .GetString(((HashMap<String, Object>) list.get(i))
                                                    .get(StringUtil.TOPIC_DOCID));
                                    for (int j = 0; j < mTopicList.size(); j++) {
                                        if (((HashMap<String, Object>) mTopicList.get(j))
                                                .get(StringUtil.TOPIC_DOCID) != null
                                                && docid2.equals(StringUtil
                                                        .GetString(((HashMap<String, Object>) mTopicList
                                                                .get(j))
                                                                .get(StringUtil.TOPIC_DOCID)))) {
                                            list.remove(i);
                                            i = i - 1;
                                            j = mTopicList.size();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                Message msg = getHandler().obtainMessage(MSG_LOADING_MORE);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();

    }

    @Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);
        List<Map<String, Object>> topicData = (List<Map<String, Object>>) result;
        if (topicData == null) {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        } else if (topicData.size() == 0) {
            Toast.makeText(getActivity(), R.string.msg_loading_nomore, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        } else {
            callLoadingListViewCompleteLoadingMore(true, true);
            addData(topicData);
        }
    }

    private void setData(List<Map<String, Object>> topicData) {
    	if (topicData != null && topicData.size() > 0) {
    		synchronized (AttitudeFrament.this) {
    			cacheDocidListMap(StringUtil.TOPIC_TYPE, "0", topicData, StringUtil.TOPIC);
    			final Map<String, Object> firstAttitude = topicData.get(0);
    			
    			mTopicList = topicData;
    			mTopicAdapterList = new ArrayList<Map<String, Object>>();
    			mTopicAdapterList.addAll(topicData.subList(1, topicData.size()));
                
                final ImageView handerImage = (ImageView) mHeaderLay.findViewById(R.id.top_image);
                
                setHeaderPic(firstAttitude, handerImage, StringUtil.TOPIC_IMGSRC);
                TextView handText = (TextView) mHeaderLay.findViewById(R.id.top_text);
                handText.setText(StringUtil.GetString((firstAttitude.get(StringUtil.TOPIC_TITLE))));
                
                if (mImageDownloader == null) {
                    mImageDownloader = new BaseImageDownloader(getActivity(), null);
                    mImageDownloader.setMode(BaseImageDownloader.Mode.CORRECT);

                    BitmapDrawable defaultNewsDrawable = (BitmapDrawable) getThemeSettingsHelper()
                            .getThemeDrawable(getActivity(), R.drawable.default_news);
                    mImageDownloader.setDefaultBitmap(defaultNewsDrawable.getBitmap());
                }

                mTopicAdapter = new BasePageViewAdapter(getActivity(), mTopicAdapterList,
                        R.layout.list_item_img_nohead, new String[] {
                                StringUtil.TOPIC_TITLE, StringUtil.TOPIC_DIGEST, StringUtil.TOPIC_SUBTITLE,
                                StringUtil.TOPIC_IMGSRC
                        }, new int[] {
                                R.id.title,R.id.desc_title, R.id.comment_count, R.id.img
                        }, mImageDownloader);
                float density = getResources().getDisplayMetrics().density;
                mImageDownloader.setBitmapWandH(((int)(73 * density)), ((int)(53 * density)), "Y");
                mTopicAdapter.setDB(getDb());
                mTopicAdapter.setAdapterType("news");
                if (getListView() != null) {
                    getListView().setAdapter(mTopicAdapter);
                }
            }
        }
    }

    private void addData(List<Map<String, Object>> topicData) {
        if (topicData == null || topicData.size() == 0 || mTopicList == null
                || mTopicAdapterList == null) {
            return;
        }
        mTopicList.addAll(topicData);
        mTopicAdapterList.addAll(topicData);
        if (mTopicAdapter != null) {
            mTopicAdapter.notifyDataSetChanged();
        }
    }

    private void cacheDocidListMap(int type, String key, List<?> data, String columnID) {
        ArrayList<String> docIDList = new ArrayList<String>();
        for (int k = 0; k < data.size(); k++) {
            if (type == StringUtil.TOPIC_TYPE)
                docIDList.add(StringUtil.GetString(((Map<String, Object>) data.get(k)).get(GetColumnsInfo.DOCID_TAG)));
            else
                docIDList.add(StringUtil.GetString(((HashMap<String, Object>) data.get(k)).get(GetColumnsInfo.DOCID_TAG)));
        }
        getApplication().setDocIdListMap(type, key, docIDList, columnID);
    }

    @Override
    public boolean isNeedRefresh() {
        // TODO Auto-generated method stub
        boolean needRefresh = super.isNeedRefresh();
        if(!needRefresh){
            return needRefresh;
        }else{
            return StringUtil.isTipsAfterOfflineDownload(getActivity());
        }
        
    }
    
    @Override
    public void onApplyTheme() {
        super.onApplyTheme();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();
        
        if (mHeaderLay != null) {
            themeSettingsHelper.setTextViewColor(context,
                    (TextView) mHeaderLay.findViewById(R.id.top_text), R.color.top_text_color);
            themeSettingsHelper.setViewBackgroud(context,
                    mHeaderLay.findViewById(R.id.top_bottom_space), R.drawable.top_text_background);
        }
        if (mTopicAdapter != null) {
            mTopicAdapter.notifyDataSetChanged();
        }
    }

}
